/**
 * 名字评分和生成API接口
 */

// 测名API配置
const API_CONFIG = {
  baseUrl: 'https://api.coze.cn/v1/workflow/run',
  token: 'pat_E6ir5rTF0vXOBWW770IsTiO5LR5KanrVopE1fRLB25E2L6kThE1Aht0O3iYgKkff',
  workflowId: '7497585613257244711'
};

// 起名API配置
const NAME_GEN_CONFIG = {
  baseUrl: 'https://api.coze.cn/v1/workflow/run',
  token: 'pat_QfYqLeWi7uIOcyT3HXld5aDnGJa6GnM63GOm1v7iIpDrwfc0E0jSBeJB8beox6F2',
  workflowId: '7488699666595872787'
};

/**
 * 名字评分API
 * @param {Object} params - 请求参数
 * @param {string} params.name - 名字
 * @param {string} params.sex - 性别，男/女
 * @param {boolean} params.mean - 是否分析寓意
 * @param {boolean} params.voice - 是否分析发音
 * @param {boolean} params.gender - 是否分析性别匹配度
 * @returns {Promise<Object>} - 返回评分结果
 */
function nameAnalysis(params) {
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: '分析中...',
      mask: true
    });

    wx.request({
      url: API_CONFIG.baseUrl,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${API_CONFIG.token}`,
        'Content-Type': 'application/json'
      },
      data: {
        workflow_id: API_CONFIG.workflowId,
        parameters: {
          name: params.name,
          sex: params.sex,
          mean: params.mean,
          voice: params.voice,
          gender: params.gender
        }
      },
      success: (res) => {
        wx.hideLoading();
        if (res.statusCode === 200) {
          try {
            // 解析响应数据
            const responseData = JSON.parse(res.data.data);
            resolve(responseData);
          } catch (error) {
            console.error('解析API响应数据失败:', error);
            reject(new Error('解析响应数据失败'));
          }
        } else {
          console.error('API请求失败:', res);
          reject(new Error(`请求失败，状态码: ${res.statusCode}`));
        }
      },
      fail: (error) => {
        wx.hideLoading();
        console.error('API请求发送失败:', error);
        reject(error);
      }
    });
  });
}

/**
 * 解析API返回的名字寓意评分
 * @param {string} meanOutput - API返回的寓意分析JSON字符串
 * @returns {Object|null} - 解析后的寓意分析结果
 */
function parseMeaningResult(meanOutput) {
  if (!meanOutput) return null;
  
  try {
    // 尝试解析JSON
    const data = typeof meanOutput === 'string' ? JSON.parse(meanOutput) : meanOutput;
    // 兼容多层嵌套格式
    const meaningData = data.meanoutput || data;
    
    return {
      meaning: meaningData.meaning || '',
      score: parseFloat(meaningData.score) || 0,
      source: meaningData.source || '',
      quote: meaningData.quote || '',
      poem: meaningData.poem || ''
    };
  } catch (error) {
    console.error('解析寓意数据失败:', error);
    return null;
  }
}

/**
 * 解析API返回的发音评分
 * @param {string} voiceOutput - API返回的发音分析JSON字符串
 * @returns {Object|null} - 解析后的发音分析结果
 */
function parsePronunciationResult(voiceOutput) {
  if (!voiceOutput) return null;
  
  try {
    // 尝试解析JSON
    const data = typeof voiceOutput === 'string' ? JSON.parse(voiceOutput) : voiceOutput;
    
    return {
      initialsAnalysis: data.initials_analysis || '',
      initialsScore: parseInt(data.initials_score) || 0,
      finalsAnalysis: data.finals_analysis || '',
      finalsScore: parseInt(data.finals_score) || 0,
      homophonyAnalysis: data.homophony_analysis || '',
      homophonyScore: parseInt(data.homophony_score) || 0,
      toneAnalysis: data.tone_analysis || '',
      toneScore: parseInt(data.tone_score) || 0,
      totalScore: parseInt(data.total_score) || 0,
      suggestions: data.suggestions || ''
    };
  } catch (error) {
    console.error('解析发音数据失败:', error);
    return null;
  }
}

/**
 * 解析API返回的性别匹配度评分
 * @param {string} sexOutput - API返回的性别匹配分析JSON字符串
 * @returns {Object|null} - 解析后的性别匹配分析结果
 */
function parseGenderMatchResult(sexOutput) {
  if (!sexOutput) return null;
  
  try {
    // 尝试解析JSON
    const data = typeof sexOutput === 'string' ? JSON.parse(sexOutput) : sexOutput;
    
    return {
      matchScore: parseInt(data.match_score) || 0,
      reason: data.reason || ''
    };
  } catch (error) {
    console.error('解析性别匹配数据失败:', error);
    return null;
  }
}

/**
 * 真实生成名字的API
 * @param {Object} data - 请求参数
 * @returns {Promise<Object>} - 返回生成的名字结果
 */
function generateRealName(data) {
  console.log('API接收到的请求数据:', data);
  
  return new Promise((resolve, reject) => {
    wx.request({
      url: NAME_GEN_CONFIG.baseUrl,
      method: 'POST',
      timeout: 90000, // 设置为90秒超时
      header: {
        'Authorization': `Bearer ${NAME_GEN_CONFIG.token}`,
        'Content-Type': 'application/json'
      },
      data: {
        workflow_id: NAME_GEN_CONFIG.workflowId,
        parameters: {
          wuxing: data.wuxing || "",
          optimize_expect: data.optimize_expect || "",
          lastname: data.surname || "", // 直接使用 data.surname 作为 lastname 参数
          sex: data.gender || "",
          namesNum: data.nameLength || "2",
          unuse_name: data.unuse_name || "",
          allusion: data.allusion || "",
          preference: data.preference || "bazi",
          is_rare_character: data.is_rare_character || "y",
          is_complex_character: data.is_complex_character || "y",
          is_fixedname: data.is_fixedname !== undefined ? data.is_fixedname : 
                       (data.fixedChar !== undefined ? data.fixedChar : false),
          fixedposition: data.fixedposition || data.fixedPosition || "first",
          fixed_word: data.fixed_word || data.fixedCharValue || "",
          zodiac: data.zodiac || ""
        }
      },
      success: (res) => {
        console.log('API响应原始数据:', res.data);
        if (res.data && res.data.code === 0) {
          // 直接返回原始响应，由results.js负责解析
          resolve(res.data);
        } else {
          reject(new Error('API请求失败: ' + (res.data.msg || '未知错误')));
        }
      },
      fail: (err) => {
        console.error('API请求错误:', err);
        reject(err);
      }
    });
  });
}

/**
 * 生成名字的API（旧版，已废弃）
 * @param {Object} data - 请求参数
 * @returns {Promise<Object>} - 返回生成的名字结果
 */
function generateName(data) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${NAME_GEN_CONFIG.baseUrl}/generate-name`,
      method: 'POST',
      data: {
        surname: data.surname,
        gender: data.gender,
        birthDate: data.birthDate,
        birthTime: data.birthTime
      },
      success: (res) => {
        resolve(res.data);
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

/**
 * 模拟API响应（开发测试用）
 * @param {Object} data - 请求参数
 * @returns {Promise<Object>} - 返回模拟的名字结果
 */
function mockGenerateName(data) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        names: [
          { name: data.surname + '家明', meaning: '家庭美满，前途光明' },
          { name: data.surname + '志远', meaning: '志向远大' },
          { name: data.surname + '雅婷', meaning: '优雅贤淑' }
        ]
      });
    }, 500);
  });
}

module.exports = {
  nameAnalysis,
  parseMeaningResult,
  parsePronunciationResult,
  parseGenderMatchResult,
  generateRealName,
  generateName,
  mockGenerateName
}; 